import { notification, message } from "ant-design-vue";
import _ from "lodash";
import { Base64 } from "js-base64";
import { previewFileUrl } from "@/environment";
import areaData from "@/data/area-json.js";
import { getFilePathCommon } from "@/api/common.js";
/**
 *
 * @description 判断是否试qiankun环境
 * @author 翟磊
 * @date 2022-03-03
 * @param {string} keyName - key名称
 * @param {[tree]} data - 树形数据
 * @return {[string]} 函数返回值:[一维集合]
 *
 * */
export function isQiankun() {
  return window.__POWERED_BY_QIANKUN__;
}

// 判断是否是纯粹对象
function isPlainObject(obj) {
  return Object.prototype.toString.call(obj) === "[object Object]";
}

//对象合并
export function deepMerge() {
  const args = _.cloneDeep(Array.from(arguments));
  if (args.length < 2) return args[0];
  let result = args[0];
  args.shift();
  args.forEach((item) => {
    if (isPlainObject(item)) {
      if (!isPlainObject(result)) result = {};
      for (let key in item) {
        if (result[key] && isPlainObject(item[key])) {
          result[key] = deepMerge(result[key], item[key]);
        } else {
          result[key] = item[key];
        }
      }
    } else if (item instanceof Array) {
      if (!(result instanceof Array)) result = [];
      item.forEach((arrItem, arrIndex) => {
        if (isPlainObject(arrItem)) {
          result[arrIndex] = deepMerge(result[arrIndex]);
        } else {
          result[arrIndex] = arrItem;
        }
      });
    }
  });
  return result;
}

/**
 *
 * @description Notification 通知提醒框
 * @author 翟磊
 * @date 2022-03-08
 * @param {string} title - 标题
 * @param {string} type - 类型
 * @param {string} description - 文案
 *
 * */
export function notificationTip(type, text, title = "提示", time = 2) {
  notification[type]({
    message: title,
    duration: time,
    description: text,
  });
}

//下载二进制文件流文件
export function downLoadFileByArraybuffer(fileStream, fileName = "") {
  let blob = new Blob([fileStream], { type: "application/vnd.ms-excel" });
  const fileReader = new FileReader();
  fileReader.readAsText(blob, "utf-8");
  fileReader.onload = () => {
    try {
      let { msg } = JSON.parse(fileReader.result);
      message.warning(msg || "下载失败请稍后重试！");
    } catch (error) {
      let name = "";
      if (!fileStream) {
        let date = new Date();
        name =
          date.getFullYear() +
          "-" +
          (date.getMonth() + 1) +
          "-" +
          date.getDate() +
          "(" +
          date.getHours() +
          "." +
          date.getMinutes() +
          "." +
          date.getSeconds() +
          ")";
      } else {
        name = fileName;
      }

      if (typeof window.navigator.msSaveBlob !== "undefined") {
        window.navigator.msSaveBlob(
          new Blob([fileStream], { type: "application/vnd.ms-excel" }),
          name + ".xls"
        );
      } else {
        let url = window.URL.createObjectURL(
          new Blob([fileStream], { type: "application/vnd.ms-excel" })
        );
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        // link.setAttribute("download", name + ".xls");
        link.setAttribute("download", name);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); //下载完成移除元素
        window.URL.revokeObjectURL(url); //释放掉blob对象
      }
    }
  };
}

// 获取当前日期
export function getNowDateStr(showTime = false) {
  let date = new Date();
  const YY = date.getFullYear();
  const MM =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1;
  const DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  const hh = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  const mm =
    date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  const ss =
    date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  let nowDate = showTime
    ? [YY, MM, DD].join("-") + " " + [hh, mm, ss].join(":")
    : [YY, MM, DD].join("-");
  return nowDate;
}

// 批量下载二进制文件流 压缩包
export function downLoadBatchFileByArraybuffer(fileStream, fileName = "") {
  let name = "";
  if (!fileStream) {
    let date = new Date();
    name =
      date.getFullYear() +
      "-" +
      (date.getMonth() + 1) +
      "-" +
      date.getDate() +
      "(" +
      date.getHours() +
      "." +
      date.getMinutes() +
      "." +
      date.getSeconds() +
      ")";
  } else {
    name = fileName;
  }
  const blob = new Blob([fileStream], {
    type: "application/zip",
  });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(url);
}

// 批量下载二进制文件流 word
export function downLoadWordFileByArraybuffer(fileStream, fileName = "") {
  let name = "";
  if (!fileStream) {
    let date = new Date();
    name =
      date.getFullYear() +
      "-" +
      (date.getMonth() + 1) +
      "-" +
      date.getDate() +
      "(" +
      date.getHours() +
      "." +
      date.getMinutes() +
      "." +
      date.getSeconds() +
      ")";
  } else {
    name = fileName;
  }
  const blob = new Blob([fileStream], {
    type: "application/msword",
  });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(url);
}

//指定长度和基数
export function _getUUID(len, radix) {
  var chars =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  var uuid = [],
    i;
  radix = radix || chars.length;
  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
  } else {
    var r;
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
    uuid[14] = "4";
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16);
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return uuid.join("");
}

/**
 *
 * @description 根据key值，返回当前链路的数据
 * @author 翟磊
 * @date 2020-03-06
 * @param {string} key - 目标值
 * @param {string} keyName - key名称
 * @param {[tree]} data - 树形数据
 * @return {[json]} 函数返回值:当前链路的数据
 * @return {boolean} hasChild 是否包含子节点数据 默认：true
 *
 * */
export function getLinkDataByKey(
  key,
  keyName,
  data,
  hasChild = true,
  children = "child"
) {
  let cloneData = _.cloneDeep(data);
  try {
    //step1 获取当前链路的到所有key集合
    let linKeys = getPathByKey(key, keyName, data, hasChild).map(
      (v) => v[keyName]
    );
    //step 2 过滤数据
    filterData(key, cloneData);

    function filterData(key, data) {
      data.forEach((v, i) => {
        if (!linKeys.includes(v[keyName])) {
          let parentNode = getParentNodeByKey(v[keyName], keyName, cloneData);
          if (!parentNode) {
            cloneData = cloneData.filter((item) =>
              linKeys.includes(item[keyName])
            );
          } else {
            if (parentNode[children]) {
              parentNode[children] = parentNode[children].filter((item) =>
                linKeys.includes(item[keyName])
              );
            }
          }
        }
        if (v.children && Array.isArray(v.children)) {
          filterData(v[keyName], v.children);
        }
      });
    }
    throw cloneData;
  } catch (e) {
    return e;
  }
}

/**
 *
 * @description 根据树中某一节点的key获取该节点所在路径中所有节点结合（最顶层父节点 ==> 当前节点）
 * @author 翟磊
 * @date 2020-03-06
 * @param {string} key - 目标值
 * @param {string} keyName - key名称
 * @param {[tree]} data - 树形数据
 * @return {[json]} 函数返回值:[节点集合]
 *
 * */
export function getPathByKey(
  key,
  keyName,
  data,
  hasChild = false,
  children = "child"
) {
  let tempPathKeys = [];
  try {
    function getNodePath(node) {
      tempPathKeys.push(node);
      if (node[keyName] === key) {
        if (
          hasChild === true &&
          node[children] &&
          Array.isArray(node[children])
        ) {
          let cAllKeys = flatTreeData(node[children]);
          tempPathKeys = [...tempPathKeys, ...cAllKeys];
        } else {
          tempPathKeys = tempPathKeys;
        }
        throw tempPathKeys;
      }
      if (node[children] && node[children].length > 0) {
        for (var i = 0; i < node[children].length; i++) {
          getNodePath(node[children][i]);
        }
        tempPathKeys.pop();
      } else {
        tempPathKeys.pop();
      }
    }
    for (let i = 0; i < data.length; i++) {
      getNodePath(data[i]);
    }
    throw [];
  } catch (e) {
    return e;
  }
}

/**
 *
 * @description 根据key值，查询当前节点数据
 * @author 翟磊
 * @date 2022-03-23
 * @param {string} key - 目标值
 * @param {string} keyName - key名称
 * @param {[tree]} data - 树形数据
 * @return {string | number} 函数返回值:父节点
 *
 * */
export function getNodeByKey(key, keyName, data, children = "child") {
  let node;
  try {
    getData(data);

    function getData(data) {
      data.forEach((v, i) => {
        if (key == v[keyName]) {
          node = v;
          throw v;
        }
        if (v[children] && Array.isArray(v[children])) {
          getData(v[children]);
        }
      });
    }
  } catch (e) {
    return e;
  } finally {
    // !node && console.warn("查无此节点，请检查key值是否正确");
  }
}

/**
 *
 * @description 扁平化tree数据
 * @author 翟磊
 * @date 2022-03-23
 * @param {string} keyName - key名称
 * @param {[tree]} data - 树形数据
 * @return {[string]} 函数返回值:[一维集合]
 *
 * */
export function flatTreeData(data, keyName = "child") {
  let keys = [];
  try {
    getKey(data);
    function getKey(data) {
      data.length > 0 &&
        data.forEach((v) => {
          keys.push(v);
          if (v[keyName] && Array.isArray(v[keyName])) {
            getKey(v[keyName]);
          }
        });
    }
    throw keys;
  } catch (keys) {
    return keys;
  }
}

//校验手机号吗
export function checkPhone(phone = "") {
  var reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
  return reg.test(phone);
}

/**
 *
 * @description 为节点添加自定义属性
 * @author 翟磊
 * @date 2022-03-23
 * @param {string} key - 目标值-传null，全级添加
 * @param {string} attName - 属性名
 * @param {string} value - 属性值
 * @param {[tree]} data - 树形数据源
 * */
export function addAttributeByKey(
  key,
  attName,
  value = null,
  data,
  children = "child"
) {
  try {
    if (key) {
      let itemNode = getNodeByKey(key, data);
      itemNode[attName] = value;
    } else {
      getData(data);
      function getData(data) {
        data.forEach((v) => {
          v[attName] = value;
          if (v.hasOwnProperty("disabled")) {
            v.disabled = v.disabled == 0 ? false : true;
          }
          if (v[children] && Array.isArray(v[children])) {
            getData(v[children]);
          }
        });
      }
    }
    throw data;
  } catch (e) {
    return e;
  }
}

export function debounce(func, delay = 500) {
  var timer = null;
  return function () {
    var context = this;
    var args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      func.apply(context, args);
      timer = null;
    }, delay);
  };
}

/**
 *
 * @description 根据key值，查询父节点，返回父节点数据
 * @author 翟磊
 * @date 2020-03-06
 * @param {string} key - 目标值
 * @param {string} keyName - key名称
 * @param {[tree]} data - 树形数据
 * @return {string | number} 函数返回值:父节点
 *
 * */
export function getParentNodeByKey(key, keyName, data, children = "childs") {
  let parentData = null,
    hasFlag = false;
  try {
    getKey(keyName, data);
    function getKey(keyName, data, parent) {
      data.forEach((v, i) => {
        parentData = parent;
        if (v[keyName] == key) {
          hasFlag = true;
          throw parentData;
        }
        if (v[children] && Array.isArray(v[children])) {
          getKey(keyName, v[children], v);
        }
      });
    }
  } catch (e) {
    return e;
  }
}

/*
 * @param { String } params
 * @desc 二维码拼接 '?token=asds&userId=sd&deptId=282'
 */
export function chartString(params) {
  let result = "?";
  for (let key in params) {
    if (params.hasOwnProperty(key)) {
      result += key + "=" + params[key] + "&";
    }
  }
  return result && result.slice(0, -1);
}

export function convertCurrency(money) {
  //汉字的数字
  var cnNums = new Array(
    "零",
    "壹",
    "贰",
    "叁",
    "肆",
    "伍",
    "陆",
    "柒",
    "捌",
    "玖"
  );
  //基本单位
  var cnIntRadice = new Array("", "拾", "佰", "仟");
  //对应整数部分扩展单位
  var cnIntUnits = new Array("", "万", "亿", "兆");
  //对应小数部分单位
  var cnDecUnits = new Array("角", "分", "毫", "厘");
  //整数金额时后面跟的字符
  var cnInteger = "整";
  //整型完以后的单位
  var cnIntLast = "元";
  //最大处理的数字
  var maxNum = 999999999999999.9999;
  //金额整数部分
  var integerNum;
  //金额小数部分
  var decimalNum;
  //输出的中文金额字符串
  var chineseStr = "";
  //分离金额后用的数组，预定义
  var parts;
  // 传入的参数为空情况
  if (money == "") {
    return "";
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    return "";
  }
  // 传入的参数为0情况
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  // 转为字符串
  money = money.toString();
  // indexOf 检测某字符在字符串中首次出现的位置 返回索引值（从0 开始） -1 代表无
  if (money.indexOf(".") == -1) {
    integerNum = money;
    decimalNum = "";
  } else {
    parts = money.split(".");
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //转换整数部分
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0;
    let IntLen = integerNum.length;
    for (let i = 0; i < IntLen; i++) {
      let n = integerNum.substr(i, 1);
      let p = IntLen - i - 1;
      let q = p / 4;
      let m = p % 4;
      if (n == "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    // 最后+ 元
    chineseStr += cnIntLast;
  }
  // 转换小数部分
  if (decimalNum != "") {
    let decLen = decimalNum.length;
    for (let i = 0; i < decLen; i++) {
      let n = decimalNum.substr(i, 1);
      if (n != "0") {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == "") {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == "") {
    chineseStr += cnInteger;
  }

  return chineseStr;
}

/*
 * 文件预览
 * @param { String } filePath --文件地址
 * @return {string } 加密后的文件预览地址
 */
export function kkFileView(filePath) {
  return (
    previewFileUrl +
    "/onlinePreview?url=" +
    encodeURIComponent(Base64.encode(filePath))
  );
}

//预览通用方法
export function commonViewFile(domain, id) {
  getFilePathCommon(domain, id)
    .then((res) => {
      let { data } = res;
      let url = data?.result ? data?.result.split("filename=")[0] : "";
      if (url) {
        window.open(kkFileView(url));
      } else {
        console.error("文件地址异常");
      }
    })
    .catch((_) => {
      console.error("文件地址异常");
    });
}

//预览下载方法
export function commonDownloadFile(domain, id, name = "", type = "") {
  getFilePathCommon(domain, id)
    .then((res) => {
      let { data } = res;
      let url = data?.result ? data?.result.split("filename=")[0] : "";
      if (url) {
        if (isImgType(type)) {
          window.open(url + "filename=" + name, "_blank");
        } else {
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", name);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      } else {
        console.error("文件地址异常");
      }
    })
    .catch((_) => {
      console.error("文件地址异常");
    });
}

function isImgType(type) {
  let types = [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".pdf", ".txt"];
  return types.includes(type);
}

export function resetTreeData(
  data,
  key,
  children = "children",
  pKeyName = "parentId"
) {
  try {
    recursiveData(data, null);

    function recursiveData(data, parent) {
      data.forEach((item, i) => {
        if (parent) {
          item[pKeyName] = parent[key];
        } else {
          item[pKeyName] = null;
        }
        if (item[children] && Array.isArray(item[children])) {
          recursiveData(item[children], item);
        }
      });
    }
    throw data;
  } catch (e) {
    return e;
  }
}

//数组分隔
export function splitArr(arr, size = 1) {
  let index = 0;
  let res = [];
  while (index < arr.length) {
    res.push(arr.slice(index, index + size));
    index += size;
  }
  return res;
}

//查询项目默认经纬度
export function getFindLonLat(obj = {}, array = []) {
  let xy = array.find((item) => item.proCode == obj.tenantCode);
  return xy;
}

//查询项目初始化经纬度坐标
export function getProInitGeo() {
  //默认【北京】
  let defaultGeo = [116.4, 39.91];
  let { tenantCode = "" } = JSON.parse(
    localStorage.getItem("ORGANIZATION") || "{}"
  );
  let projectSource = JSON.parse(
    localStorage.getItem("PROJECT_SOURCE") || "[]"
  );
  //校验规则
  let lngRules =
    /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,20})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,20}|180)$/;
  let latRules = /^(\-|\+)?([0-8]?\d{1}\.\d{0,20}|90\.0{0,20}|[0-8]?\d{1}|90)$/;
  let lonRe = new RegExp(lngRules);
  let latRe = new RegExp(latRules);
  if (
    tenantCode ||
    projectSource.length == 0 ||
    !projectSource.some((v) => tenantCode && v.proCode == tenantCode)
  ) {
    let v = projectSource.find((item) => item.proCode == tenantCode);
    let geox = v?.geox ?? "";
    let geoy = v?.geoy ?? "";
    if (lonRe.test(geox) && latRe.test(geoy) && geox && geoy) {
      return [geox, geoy];
    } else {
      return defaultGeo;
    }
  } else {
    return defaultGeo;
  }
}

//更具url下载文件
export function downFileByUrl(fileUrl = "", fileName = "") {
  let downloadElement = document.createElement("a");
  downloadElement.href = fileUrl;
  if (fileName) {
    //下载后文件名
    downloadElement.download = name;
  }
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);
}

/*
 * 当type=1时获取出生日期,type=2时获取性别,type=3时获取年龄
 * */
export function parseCardInfo(IdCard, type) {
  if (!isCardID(IdCard)) {
    console.warn("身份证号错误");
    return "";
  }
  if (type === 1) {
    //获取出生日期
    let birthday =
      IdCard.substring(6, 10) +
      "-" +
      IdCard.substring(10, 12) +
      "-" +
      IdCard.substring(12, 14);
    return birthday;
  }
  if (type === 2) {
    //获取性别
    if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
      return "男";
    } else {
      return "女";
    }
  }
  if (type === 3) {
    //获取年龄
    var ageDate = new Date();
    var month = ageDate.getMonth() + 1;
    var day = ageDate.getDate();
    var age = ageDate.getFullYear() - IdCard.substring(6, 10) - 1;
    if (
      IdCard.substring(10, 12) < month ||
      (IdCard.substring(10, 12) === month && IdCard.substring(12, 14) <= day)
    ) {
      age++;
    }
    if (age <= 0) {
      age = 1;
    }
    return age;
  }

  //籍贯
  if (type == 4) {
    //省份
    let provinceNo = IdCard.substr(0, 2);
    let provinceName = getNodeByKey(
      provinceNo,
      "code",
      areaData,
      "children"
    )?.name;
    //市
    let cityNo = IdCard.substr(2, 2);
    let cityName = getNodeByKey(
      provinceNo + cityNo + "00",
      "code",
      areaData,
      "children"
    )?.name;
    //区
    let areaNo = IdCard.substr(4, 2);
    let areaName = getNodeByKey(
      provinceNo + cityNo + areaNo,
      "code",
      areaData,
      "children"
    )?.name;
    return [
      { code: provinceNo, name: provinceName },
      { code: provinceNo + cityNo + "00", name: cityName },
      { code: provinceNo + cityNo + areaNo, name: areaName },
    ];
  }
}

export function isCardID(sId) {
  let iSum = 0;
  let aCity = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    71: "台湾",
    81: "香港",
    82: "澳门",
    91: "国外",
  };
  // 你输入的身份证长度或格式错误
  if (!/^\d{17}(\d|x)$/i.test(sId)) return false;
  sId = sId.replace(/x$/i, "a");
  //你的身份证地区非法
  if (aCity[parseInt(sId.substr(0, 2))] == null) return false;
  let sBirthday =
    sId.substr(6, 4) +
    "-" +
    Number(sId.substr(10, 2)) +
    "-" +
    Number(sId.substr(12, 2));
  let d = new Date(sBirthday.replace(/-/g, "/"));
  //身份证上的出生日期非法
  if (
    sBirthday !=
    d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()
  )
    return false;
  for (let i = 17; i >= 0; i--)
    iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
  //你输入的身份证号非法
  if (iSum % 11 != 1) return false;
  return true;
}

/**
 * 解决两个数相加精度丢失问题
 * @param a
 * @param b
 * @returns {Number}
 */
export function floatAdd(a, b) {
  var c, d, e;
  if (undefined == a || null == a || "" == a || isNaN(a)) {
    a = 0;
  }
  if (undefined == b || null == b || "" == b || isNaN(b)) {
    b = 0;
  }
  try {
    c = a.toString().split(".")[1].length;
  } catch (f) {
    c = 0;
  }
  try {
    d = b.toString().split(".")[1].length;
  } catch (f) {
    d = 0;
  }
  e = Math.pow(10, Math.max(c, d));
  return (floatMul(a, e) + floatMul(b, e)) / e;
}

/**
 * 解决两个数相减精度丢失问题
 * @param a
 * @param b
 * @returns {Number}
 */
export function floatSub(a, b) {
  var c, d, e;
  if (undefined == a || null == a || "" == a || isNaN(a)) {
    a = 0;
  }
  if (undefined == b || null == b || "" == b || isNaN(b)) {
    b = 0;
  }
  try {
    c = a.toString().split(".")[1].length;
  } catch (f) {
    c = 0;
  }
  try {
    d = b.toString().split(".")[1].length;
  } catch (f) {
    d = 0;
  }
  e = Math.pow(10, Math.max(c, d));
  return (floatMul(a, e) - floatMul(b, e)) / e;
}

/**
 * 解决两个数相乘精度丢失问题
 * @param a
 * @param b
 * @returns {Number}
 */

export function floatMul(a, b) {
  var c = 0,
    d = a.toString(),
    e = b.toString();
  try {
    c += d.split(".")[1].length;
  } catch (f) {}
  try {
    c += e.split(".")[1].length;
  } catch (f) {}
  return (
    (Number(d.replace(".", "")) * Number(e.replace(".", ""))) / Math.pow(10, c)
  );
}

/**
 * 解决两个数相除精度丢失问题
 * @param a
 * @param b
 * @returns
 */
export function floatDiv(a, b) {
  var c,
    d,
    e = 0,
    f = 0;
  try {
    e = a.toString().split(".")[1].length;
  } catch (g) {}
  try {
    f = b.toString().split(".")[1].length;
  } catch (g) {}
  return (
    (c = Number(a.toString().replace(".", ""))),
    (d = Number(b.toString().replace(".", ""))),
    floatMul(c / d, Math.pow(10, f - e))
  );
}

/**
 * 根据层级获取节点  树形表格 默认展开多少层级
 * @param {*} list 数据
 * @param {*} hierarchy 层级
 * @param {*} nodeName 子节点的名称
 * @returns 结果
 */
export function getNodeByHierarchy(list, hierarchy, nodeName = "children") {
  if (list && list.length) {
    if (hierarchy > 1) {
      const allRow = [];
      list.forEach((item) => {
        allRow.push(item);
        if (item[nodeName]) {
          allRow.push(
            ...getNodeByHierarchy(item[nodeName], hierarchy - 1, nodeName)
          );
        }
      });

      return allRow;
    } else if (hierarchy === 1) {
      return list;
    } else return [];
  } else return [];
}
